// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')

function sum(arr) {
  return arr.reduce(function (prev, curr, idx, arr) {
    return prev + curr
  })
}

function parseTime(time, cFormat) {
  if (time == null) {
    time = Date.now()
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

function checkIsClose() {
  let hour = (new Date()).getHours() + 8 // 服务端时间+8 才是客户端时间
  return hour >= 15
}

function jsonpToJson(datas) {
  let jsonData = null
  // 下面是对获取到的数据进行处理，把jsonp格式的数据处理成json格式的数据
  if (typeof datas === 'string') {
    jsonData = datas.slice(8, -2)
    jsonData = JSON.parse(jsonData)
  }
  return jsonData
}

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
// 云函数入口函数
/**
 * 3种情况的返回结果
 */
exports.main = async (event, context) => {
  // 获取时间
  const today = parseTime(null, '{y}-{m}-{d}')
  // const isClose = checkIsClose()
  const industysCollecction = db.collection('industrys')
  const { data: industys } = await industysCollecction.get()
  let datas = []

  for (let i = 0, len = industys.length; i < len; i++) {

    let currentIndusty = industys[i]
    let { type, code } = currentIndusty
    let needUpdateTrend = false
    let old_trend_value = Number(currentIndusty.trend_value)

    currentIndusty.date = today

    let daysRes = await axios({
      url: `http://img1.money.126.net/data/hs/kline/day/times/${type}${code}.json`,
      method: 'get'
    })
    // 计算20日均值
    if (daysRes.data) {
      let len = 20
      let closes = daysRes.data.closes.slice(len * -1)
      let ma = sum(closes) / len
      currentIndusty.ma20day = ma.toFixed(2)
      currentIndusty.ma20day_fix = (currentIndusty.ma20day / (1 + 0.01)).toFixed(2)
    }

    let weeksRes = await axios({
      url: `http://img1.money.126.net/data/hs/kline/week/times/${type}${code}.json`,
      method: 'get'
    })

    if (weeksRes.data) {
      let len = 5
      let closes = weeksRes.data.closes.slice(len * -1)
      let ma = sum(closes) / len

      if (code == '512690') {
        ma = 1.322
      }

      if (code == '510150') {
        ma = 0.833
      }

      currentIndusty.ma5week = ma.toFixed(2)
      currentIndusty.ma5week_fix = (currentIndusty.ma5week / (1 + 0.01)).toFixed(2)
    }

    // 请求估值
    let { data: guzhi } = await axios({
      url: `http://fundgz.1234567.com.cn/js/${currentIndusty.jijin_code}.js`,
      method: 'get'
    })
    guzhi = jsonpToJson(guzhi)
    currentIndusty.guzhi = guzhi.gszzl

    // 获取实时价格
    let { data: todayRes } = await axios({
      url: `http://img1.money.126.net/data/hs/time/today/${type}${code}.json`,
      method: 'get'
    })
    let currentValue = todayRes.data.slice(-1)[0][1]


    // 计算累积涨跌幅 （当前价格 - 上一次价格）/ 上一次价格 * 100
    currentIndusty.totalChg = (((currentValue - currentIndusty.lastPrice) / currentIndusty.lastPrice) * 100).toFixed(2)
    // 今日涨跌幅 （当前价格 - 前一日收盘价）/ 前一日收盘价 * 100
    // currentIndusty.Chg = (((currentValue - todayRes.yestclose) / todayRes.yestclose) * 100).toFixed(2)

    // 上升时 若满足条件则更新为下降
    if (old_trend_value && ((currentValue < currentIndusty.ma20day_fix) && (currentValue < currentIndusty.ma5week_fix))) {
      needUpdateTrend = true
      currentIndusty.trend_value = 0
    }
    // 下降时 若满足条件则更新为上升
    if (!old_trend_value && ((currentValue >= currentIndusty.ma20day * 1.01) && (currentValue >= currentIndusty.ma5week * 1.01))) {
      needUpdateTrend = true
      currentIndusty.trend_value = 1
    }

    if (needUpdateTrend) {
      currentIndusty.lastPrice = currentValue
      currentIndusty.lastModify = parseTime(null, '{y}-{m}-{d}')
    }

    currentIndusty.needUpdateTrend = needUpdateTrend
    currentIndusty.currentValue = currentValue

    datas.push(currentIndusty)

    if (needUpdateTrend) {
      industysCollecction.where({ code }).update({
        data: {
          trend_value: currentIndusty.trend_value,
          lastModify: currentIndusty.lastModify,
          lastPrice: currentIndusty.lastPrice,
          date: currentIndusty.date,
          ma20day: currentIndusty.ma20day,
          ma20day_fix: currentIndusty.ma20day_fix,
          ma5week: currentIndusty.ma5week,
          ma5week_fix: currentIndusty.ma5week_fix,
        }
      })
    } else {
      industysCollecction.where({ code }).update({
        data: {
          date: currentIndusty.date,
          ma20day: currentIndusty.ma20day,
          ma20day_fix: currentIndusty.ma20day_fix,
          ma5week: currentIndusty.ma5week,
          ma5week_fix: currentIndusty.ma5week_fix,
        }
      })
    }

  }

  return {
    datas
  }
}


